from threading import Thread, Lock, RLock
from time import sleep

# 共享资源
num = 0
# lock = Lock()
# 在一个线程内可以对锁进行重复加锁
lock = RLock()


class MyThread(Thread):
    def fun1(self):
        global num
        with lock:
            num -= 1

    def fun2(self):
        global num
        if lock.acquire():
            num += 1
            if num > 5:
                self.fun1()
            print('Num=', num)
            lock.release()

    def run(self):
        while True:
            sleep(2)
            self.fun2()


t = MyThread()
t.start()
t.join()
